package org.zuel.huhuForum.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zuel.huhuForum.component.SendMsg;
import org.zuel.huhuForum.constant.CommunityConstant;
import org.zuel.huhuForum.model.DiscussPost;
import org.zuel.huhuForum.param.Event;
import org.zuel.huhuForum.param.Page;
import org.zuel.huhuForum.service.IDiscussPostService;
import org.zuel.huhuForum.service.IElasticsearchService;
import org.zuel.huhuForum.service.ILikeService;
import org.zuel.huhuForum.service.IUserService;
import org.zuel.huhuForum.util.HostHolder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.zuel.huhuForum.util.DesensitizeUtil.desensitize;

@RestController
@RequestMapping("/search")
@Api(tags = "检索")
@Log4j2
public class SearchController implements CommunityConstant{
    @Autowired
    private IElasticsearchService elasticsearchService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IDiscussPostService discussPostService;

    @Autowired
    private ILikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private SendMsg eventProducer;

    /**
     * 搜索
     * search?keword=xxx
     * @param keyword 关键词
     * @param current
     * @return
     */
    @CrossOrigin
    @PostMapping("/search")
    @ApiOperation(value = "搜索")
    public Map<String, Object> search(@RequestParam(name="keyword", required = true)String keyword
            , @RequestParam(name = "current",required = false) Integer current) {
        Page page=new Page();
        if(current!=null){
            page.setCurrent(current);
        }
        Integer id;
        if(hostHolder.getUser()==null){
            log.info("游客登录");
             id=0;
        }else {
             id=hostHolder.getUser().getId();
        }
        Event event=new Event();
        event.setTopic("search")
                .setUserId(id)
                .setData("keyword", keyword);
        eventProducer.historyEvent(event);

        Map<String, Object>model=new HashMap<>();
        // 搜索帖子 (Spring 提供的 Page 当前页码从 0 开始计数)
        org.springframework.data.domain.Page<DiscussPost> searchResult =
                elasticsearchService.searchDiscussPost(keyword, page.getCurrent()-1, page.getLimit());
        if(searchResult==null){
            model.put("data", "暂无查询结果！");
            model.put("code", "23");
            model.put("msg", "null");
            return model;
        }
        // 聚合数据
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (searchResult != null) {
            for (DiscussPost post : searchResult) {
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                // 作者
                map.put("user",desensitize(userService.findUserById(post.getUserId())));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                discussPosts.add(map);
            }
        }else{
            log.info("检索失败...");
        }

        model.put("discussPosts", discussPosts);
        model.put("keyword", keyword);
        model.put("page",page);
        // 设置分页
        page.setPath("/search?keyword="+ keyword);
        page.setRows(searchResult == null ? 0 : (int) searchResult.getTotalElements());

        return model;
    }
    @CrossOrigin
    @PostMapping("/add")
    @ApiOperation(value = "添加")
    public Object add(@RequestParam(name="postid", required = true)Integer id) {
        DiscussPost post=discussPostService.findDiscussPostById(id);
        log.info("post is "+post.toString()+",content is "+post.getContent());
        elasticsearchService.saveDiscusspost(post);
        List<DiscussPost> list= elasticsearchService.searchs(post.getTitle(), 0, 5);
        return list;
    }

}
